home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / The World of Computer Software.iso / snpd1292.zip / DAYNUM.C < prev    next >
C/C++ Source or Header  |  1992-12-26  |  2KB  |  91 lines

  1. /*
  2. **  DAYNUM.C - Functions to return statistics about a given date.
  3. **
  4. **  public domain by Bob Stout - uses Ray Gardner's SCALDATE.C
  5. */
  6.  
  7. long ymd_to_scalar (unsigned yr, unsigned mo, unsigned day);
  8. static long jan1date;
  9.  
  10. /*
  11. **  Define ISO to be 1 for ISO (Mon-Sun) calendars
  12. **
  13. **  ISO defines the first week with 4 or more days in it to be week #1.
  14. */
  15.  
  16. #ifndef ISO
  17.  #define ISO 0
  18. #endif
  19.  
  20. #if (ISO != 0 && ISO != 1)
  21.  #error ISO must be set to either 0 or 1
  22. #endif
  23.  
  24. /*
  25. **  Determine if a given date is valid
  26. */
  27.  
  28. int valiDate(unsigned yr, unsigned mo, unsigned day)
  29. {
  30.       unsigned int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  31.  
  32.       if (1 > mo || 12 < mo)
  33.             return 0;
  34.       if (1 > day || day > (days[mo - 1] + (2 == mo && isleap(yr))))
  35.             return 0;
  36.       else  return 1;
  37. }
  38.  
  39. /*
  40. **  Return the day of the year (1 - 365/6)
  41. */
  42.  
  43. int daynum(int year, int month, int day)
  44. {
  45.       jan1date = ymd_to_scalar(year, 1, 1);
  46.       return (int)(ymd_to_scalar(year, month, day) - jan1date + 1L);
  47. }
  48.  
  49. /*
  50. **  Return the week of the year (1 - 52)
  51. */
  52.  
  53. int weeknum(int year, int month, int day)
  54. {
  55.       int wn, j1n, dn = daynum(year, month, day);
  56.  
  57.       dn += (j1n = (int)((jan1date - (long)ISO) % 7L)) - 1;
  58.       wn = dn / 7;
  59.       if (ISO)
  60.             wn += (j1n < 4);
  61.       else  ++wn;
  62.       return wn;
  63. }
  64.  
  65. #ifdef TEST
  66.  
  67. #include <stdio.h>
  68. void do_err(void);
  69.  
  70. void main(int argc, char *argv[])
  71. {
  72.       int day, month, year;
  73.  
  74.       if (4 > argc)
  75.       {
  76.             puts("Usage: DAYNUM month day year");
  77.             return;
  78.       }
  79.  
  80.       month = atoi(argv[1]);
  81.       day   = atoi(argv[2]);
  82.       year  = atoi(argv[3]);
  83.       if (100 > year)
  84.             year += 1900;
  85.  
  86.       printf("%d/%d/%d is day #%d in week %d\n", month, day, year,
  87.             daynum(year, month, day), weeknum(year, month, day));
  88. }
  89.  
  90. #endif /* TEST */
  91.